﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataAccess;
using Utility;
using Data;
namespace Website.UC
{
    public partial class UCSubject : System.Web.UI.UserControl
    {
        Tbl_SubjectBUS subjectBus = new Tbl_SubjectBUS();
        Tbl_MajorBUS majorBus = new Tbl_MajorBUS();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                loadData();
                loadMajor();
            }
        }
        private void loadMajor()
        {
            foreach (tbl_major m in majorBus.getListMajor())
            {
                DropDownList1.Items.Add(m.major_name + "-" + m.major_id);
            }
            DropDownList1.DataBind();
        }
        private void loadData()
        {
            GridView1.DataSource = subjectBus.getListSubject();
            GridView1.DataBind();
        }
        protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            lblId.Text = WebHelper.GetValueGridView(GridView1, 2, e);
            txtName.Text = WebHelper.GetValueGridView(GridView1, 3, e);
        }
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {

            tbl_subject ts = new tbl_subject();
            ts.subject_id = Int32.Parse(WebHelper.GetDataKey(GridView1 , e));
            subjectBus.deleteSubject(ts);
            loadData();
            reset();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (txtName.Text.Length == 0)
            {
                WebHelper.ShowMessage("Name not null", Page);
            }
            else
            {
                tbl_subject ts = new tbl_subject();
                ts.subject_name = txtName.Text;
                ts.major_id = Int32.Parse(DropDownList1.SelectedValue.ToString().Split('-')[1].ToString());

                if (lblId.Text.Length == 0)
                {
                    subjectBus.insertSubject(ts);
                }
                else
                {
                    ts.subject_id = Int32.Parse(lblId.Text);
                    subjectBus.updateSubject(ts);
                }
                reset();
                loadData();
            }


        }

        private void reset()
        {
            lblId.Text = "";
            txtName.Text = "";
        }

       
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            reset();
        }
    }
    
}